/*
 * ConfigurableEndsWithFilenameFilter.java
 * 
 * Copyright (C) 2010 no.good.at.coding
 * 
 * This file is part of the NoGoodCommons Library.
 *
 * The NoGoodCommons Library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.nogoodatcoding.commons;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

/**
 * 
 * Implements a {@link FilenameFilter} based on the string passed to the constructer.
 * 
 * The string can be an extension or a list of pipe separated values of extensions (because pipes are not allowed in the filenames (AFAIK!)).
 * 
 * (Can also be used for non-extension checking but keep in mind that the {@code accept()} method essentially checks if the filename ends with the
 * given value)
 * 
 * @author no.good.at.coding
 */
public class ConfigurableEndsWithFilenameFilter implements FilenameFilter
{

    private static Logger log = Logger.getLogger(ConfigurableEndsWithFilenameFilter.class);
    private static ResourceBundle bundle = ResourceBundle
            .getBundle("com.nogoodatcoding.commons.messages.Messages_ConfigurableEndsWithFilenameFilter");

    private String[] arrayOfExtensions = null;

    private boolean isCaseSensitive = true;

    /**
     * 
     * Returns a new {@code ConfigurableEndsWithFilenameFilter} object if the extensions given are non null and not empty/whitespace. If they are, a
     * null is returned to avoid the overhead of calling {@code accept()} when we know all files will match
     * 
     * @param extensions
     *            A list of PSV (pipe separated values) of extensions that should be accepted by this filter. If it's null/empty/only whitespace, a
     *            null will be returned. Any whitespace before and after the pipe will be ignored. The extensions should not be in the format of
     *            {@code *.avi|*.txt|*.java} etc. The asterisks and period symbols will treated as literals. Use the format {@code avi|txt|java}
     *            instead.
     * 
     * @param isCaseSensitive
     *            Indicates if the matches will be case sensitive or not (keep in mind *nix sytems when setting to {@code false})
     * 
     * @return null if extensions is null or empty; a {@code ConfigurableEndsWithFilenameFilter} object otherwise
     * 
     * @see com.nogoodatcoding.commons.ConfigurableEndsWithFilenameFilter#getInstance(java.lang.String)
     * 
     */
    public static ConfigurableEndsWithFilenameFilter getInstance(String extensions, boolean isCaseSensitive)
    {
        log.trace(String.format(bundle.getString("log.trace.arguments"), extensions, isCaseSensitive));

        ConfigurableEndsWithFilenameFilter ConfigurableEndsWithFilenameFilterToReturn = null;
        // if null, or empty/only whitespace, we'll return a null object
        // so that the overhead of calling accept when we know everything
        // will match is avoided
        if (extensions == null || extensions.trim().isEmpty())
        {
            log.warn(bundle.getString("log.warn.extensions.null"));
        }
        else
        {
            ConfigurableEndsWithFilenameFilterToReturn = new ConfigurableEndsWithFilenameFilter(extensions,
                    isCaseSensitive);
            ConfigurableEndsWithFilenameFilterToReturn.isCaseSensitive = isCaseSensitive;
        }

        return ConfigurableEndsWithFilenameFilterToReturn;
    }

    /**
     * 
     * Convenience method to call {@link ConfigurableEndsWithFilenameFilter#getInstance(java.lang.String, boolean)}.
     * 
     * @param extensions
     *            A list of PSV (pipe separated values) of extensions that should be accepted by this filter. If it's null/empty/only whitespace, a
     *            null will be returned. Any whitespace before and after the pipe will be ignored. The extensions should not be in the format of
     *            {@code *.avi| *.txt | *.java} etc. The asterisks and period symbols will treated as literals. Use the format {@code avi| txt|java}
     *            instead
     * 
     * @return null if extensions is null or empty; a {@code ConfigurableEndsWithFilenameFilter} object otherwise
     * 
     */
    public static ConfigurableEndsWithFilenameFilter getInstance(String extensions)
    {
        return ConfigurableEndsWithFilenameFilter.getInstance(extensions, true);
    }

    /**
     * 
     * Private constructor so that we can check for empty/null as the extensions to accept and return a null object to avoid overhead where all files
     * will match.
     * 
     * @param extensions
     *            list of PSV (pipe separated values) of extensions that should be accepted by this filter. Will never be null/empty; {@code
     *            getInstance()} will take care of that
     * 
     * @param isCaseSensitive
     *            If {@code true}, it means that later, comparisons will be done with lower case filename, so all extensions will be converted to
     *            lower case as well
     * 
     */
    private ConfigurableEndsWithFilenameFilter(String extensions, boolean isCaseSensitive)
    {
        log.trace(bundle.getString("log.trace.extensions.split"));

        arrayOfExtensions = extensions.split("\\s*\\|\\s*");

        if (isCaseSensitive)
        {
            for (int i = 0; i < arrayOfExtensions.length; i++)
            {
                arrayOfExtensions[i] = arrayOfExtensions[i].toLowerCase();
            }
        }

        log.trace(String.format(bundle.getString("log.trace.extensions.list"), Arrays.toString(arrayOfExtensions)));
    }

    public boolean accept(File dir, String filename)
    {
        log.trace(String.format(bundle.getString("log.trace.accept.arguments"), dir, filename));
        if (!isCaseSensitive)
        {
            log.trace(bundle.getString("log.trace.accept.not.caseSensitive"));
            filename = filename.toLowerCase();
        }

        boolean result = false;

        for (String currentExtension : arrayOfExtensions)
        {
            log.trace(String.format(bundle.getString("log.trace.accept.check.extension"), filename, currentExtension));
            if (filename.endsWith(currentExtension))
            {
                log.trace(String.format(bundle.getString("log.trace.accept.check.extension.true"), filename,
                        currentExtension));
                result = true;
                break;
            }
        }
        return result;
    }
}